import { PluginOption } from 'vite';
import chokidar, { FSWatcher } from 'chokidar';
import * as prettier from 'prettier';
import fs from 'fs';

export default function Format(): PluginOption {
  let FsWatcher: FSWatcher;
  let Cache: any = {};
  return {
    name: 'format-prettier',
    enforce: 'pre',
    apply: 'serve',
    configureServer(server: any){
      server.httpServer.on('close', () => FsWatcher.close())
    },
    config() {
      FsWatcher = chokidar.watch(["src/**/*", "example/**/*"])
      .on('change', (filepath) => {
        Cache[filepath] = Cache[filepath] || {};
        const text = fs.readFileSync(filepath, "utf8");
        if (text == Cache[filepath].file || Cache[filepath].parsing) return
        Cache[filepath].parsing = true;
        setTimeout(async () => {
          const options: any = await prettier.resolveConfig(filepath);
          const formatted = await prettier.format(text, {filepath, ...options});
          fs.writeFileSync(filepath, formatted, 'utf-8');
          Cache[filepath].file = formatted;
          Cache[filepath].parsing = false;
        }, 100)
      })
    },
  }
}